using System;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly: WebResource("SBPweb.Controls.Web.UpdatePanel.js", "text/javascript")]

namespace SBPweb.Controls.Web
{
	/// <summary>
	/// Enables sections of a page to be partially rendered without a postback.
	/// </summary>
	[ToolboxData("<{0}:UpdatePanel runat=server></{0}:UpdatePanel>")]
	public class UpdatePanel : System.Web.UI.UpdatePanel
	{

		#region Private fields

		private bool mIsBound = false;

		#endregion

		#region Constructor logic

		/// <summary>
		/// Initializes a new instance of UpdatePanel
		/// </summary>
		public UpdatePanel()
			: base()
		{
			UpdateMode = UpdatePanelUpdateMode.Conditional;
			ChildrenAsTriggers = true;
		}

		#endregion

		#region Public property accessors

		/// <summary>
		/// Returns true if the control is bound
		/// </summary>
		public bool IsBound
		{
			get
			{
				return mIsBound;
			}
			set
			{
				mIsBound = value;
			}
		}

		#endregion

		#region Override methods

		/// <summary>
		/// Occurs after the Control object is loaded but prior to rendering.
		/// </summary>
		/// <param name="e">EventArgs e</param>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			string rbClientId = string.Empty;

			foreach(UpdatePanelControlTrigger upct in Triggers)
			{
				rbClientId = upct.ControlID;
				break;
			}

			Control ctrl = this.FindControl(rbClientId);
			if (ctrl != null)
			{
				rbClientId = ctrl.ClientID;
			}

			string script = string.Format("panelsLoadedEventHandler('{0}', '{1}');", rbClientId, this.mIsBound);

			this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "SBPweb.Controls.Web.UpdatePanel.js");
			this.Page.ClientScript.RegisterStartupScript(this.GetType(), "_POSTBACK", script, true);
		}

		/// <summary>
		/// Sends server control content to a provided HtmlTextWriter object, which writes the content to be rendered on the client.
		/// </summary>
		/// <param name="writer">HtmlTextWriter writer</param>
		protected override void Render(HtmlTextWriter writer)
		{
			writer.AddAttribute("isBound", IsBound.ToString());
			base.Render(writer);
		}

		#endregion

	}
}
